'use strict';

/**
 * 获取反馈列表云函数
 * 供管理员查看和管理用户反馈
 */
exports.main = async (event, context) => {
  console.log('event : ', event);
  
  // 获取数据库引用
  const db = uniCloud.database();
  const collection = db.collection('feedback');
  
  try {
    // 获取查询参数
    const {
      page = 1,           // 页码，默认第1页
      pageSize = 10,      // 每页条数，默认10条
      status = '',        // 状态筛选
      type = '',          // 类型筛选
      priority = '',      // 优先级筛选
      keyword = '',       // 关键词搜索
      startDate = '',     // 开始日期
      endDate = ''        // 结束日期
    } = event;
    
    // 构建查询条件
    let whereCondition = {
      isDeleted: false
    };
    
    // 状态筛选
    if (status) {
      whereCondition.status = status;
    }
    
    // 类型筛选
    if (type) {
      whereCondition.type = type;
    }
    
    // 优先级筛选
    if (priority) {
      whereCondition.priority = priority;
    }
    
    // 关键词搜索（搜索姓名、联系方式、描述）
    if (keyword) {
      whereCondition.$or = [
        { name: new RegExp(keyword, 'i') },
        { contact: new RegExp(keyword, 'i') },
        { description: new RegExp(keyword, 'i') }
      ];
    }
    
    // 日期范围筛选
    if (startDate || endDate) {
      whereCondition.createTime = {};
      if (startDate) {
        whereCondition.createTime.$gte = new Date(startDate).getTime();
      }
      if (endDate) {
        whereCondition.createTime.$lte = new Date(endDate).getTime();
      }
    }
    
    // 计算跳过的数量
    const skip = (page - 1) * pageSize;
    
    // 执行查询
    const countResult = await collection.where(whereCondition).count();
    const total = countResult.total;
    
    const listResult = await collection
      .where(whereCondition)
      .orderBy('createTime', 'desc')
      .skip(skip)
      .limit(pageSize)
      .get();
    
    // 计算分页信息
    const totalPages = Math.ceil(total / pageSize);
    const hasMore = page < totalPages;
    
    // 返回结果
    return {
      code: 200,
      message: '获取反馈列表成功',
      data: {
        list: listResult.data,
        pagination: {
          page: page,
          pageSize: pageSize,
          total: total,
          totalPages: totalPages,
          hasMore: hasMore
        }
      }
    };
    
  } catch (error) {
    console.error('获取反馈列表失败:', error);
    
    return {
      code: 500,
      message: '服务器内部错误',
      data: null,
      error: error.message
    };
  }
};
